      1  import java.util.Iterator;

      2

      3  /**

      4     This program demonstrates tree traversal.

      5  */

      6  public class TraversalDemo

      7  {

      8     public static void main(String[] args)

      9     {

     10        Tree t1 = new Tree("Anne");

     11        Tree t2 = new Tree("Peter");

     12        t1.addSubtree(t2);

     13        Tree t3 = new Tree("Zara");

     14        t1.addSubtree(t3);

     15        Tree t4 = new Tree("Savannah");

     16        t2.addSubtree(t4);

     17

     18        // Count short names with visitor

     19        class ShortNameCounter implements Tree.Visitor

     20        {

     21           public int counter = 0;

     22           public void visit(Object data)

     23           {

     24              System.out.println(data);

     25              if (data.toString().length() <= 5) { counter++; }

     26           }

     27        }

     28

     29        ShortNameCounter v = new ShortNameCounter();

     30

     31        t1.preorder(v);

     32        System.out.println("Short names: " + v.counter);

     33

     34        // Count short names with iterator

     35        Iterator iter = t1.iterator();

     36        int counter = 0;

     37        while (iter.hasNext())

     38        {

     39           Object data = iter.next();

     40           System.out.println(data);

     41           if (data.toString().length() <= 5) { counter++; }

     42        }

     43        System.out.println("Short names: " + counter);

     44     }

     45  }